package com.learn.code.juc.lock;

import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author : 翌擎科技
 * @date : 2022/8/2 11:16
 */
public class LockDemoTest {

    //默认为非公平锁
    private static ReentrantLock lock = new ReentrantLock(true);



    public static void main(String[] args) {
//        new Thread(() -> testLock()).start();
//        new Thread(() -> testLock()).start();
//        new Thread(() -> testLock()).start();
//        new Thread(() -> testLock()).start();

        new Thread(() -> testLockA()).start();
        new Thread(() -> testLockA()).start();
        new Thread(() -> testLockA()).start();
        new Thread(() -> testLockA()).start();


    }

    public static void testLock() {
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + "获取锁");

            System.out.println(Thread.currentThread().getName() + "释放锁");

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public static void testLockA() {
        if (lock.tryLock()) {
            try {
                System.out.println(Thread.currentThread().getName() + "获取锁");

                System.out.println(Thread.currentThread().getName() + "释放锁");

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        } else {
            System.out.println(Thread.currentThread().getName() + "获取锁失败");

        }
    }

}
